﻿using System;
using WindowsPhone.CompactContainer.ServiceLocation.CompactContainer;

namespace WindowsPhone.CompactContainer.Aggregator
{
    /// <remarks />
    public class EventAggregatorHandler : DefaultHandler
    {
        private readonly IContainer _container;

        /// <remarks />
        public EventAggregatorHandler(IContainer container) : base(container)
        {
            _container = container;
        }

        /// <summary>
        /// Foreach type created, check if the type implements IEventHandler, if so register the type with
        /// the event publisher class.
        /// </summary>
        /// <param name="classType">The interface requested from the container.</param>
        /// <returns></returns>
        public override object Create(Type classType)
        {
            var target = base.Create(classType);

            if (typeof(IEventHandler).IsAssignableFrom(classType))
            {
                var eventPublisher = _container.Resolve<IEventPublisher>();
                eventPublisher.RegisterHandlers(target);
            }
            return target;
        }
    }
}
